/**
 * 保存用户的文章
 */

const mdModel = require("../models/mdModel");
const utils = require("../common/utils");

function getMd(body) {
  body.createTime = utils.changeTime(body.createTime);

  return new Promise((resolve, reject) => {
    mdModel.findOne({ user_id: body.user_id }, (err, suc) => {
      err ? reject(err) : resolve(suc);
    });
  }).then(async suc => {
    if (suc) {
      const user = await mdModel.findOne({ user_id: suc.user_id });
      const mdId = user.user_md.length + 1;
      return new Promise((resolve, reject) => {
        mdModel.findOneAndUpdate(
          {
            user_id: suc.user_id,
          },
          {
            $push: {
              user_md: {
                $each: [
                  {
                    id: mdId,
                    title: body.title,
                    label: body.label,
                    content: body.content,
                    createTime: body.createTime,
                    read: 0,
                    recommend: 0,
                    good: 0,
                  },
                ],
                $position: 0,
              },
            },
          },
          (err, data) => {
            err ? reject(err) : resolve(data);
          }
        );
      });
    } else {
      return new Promise((resolve, reject) => {
        new mdModel({
          user_name: body.user_name,
          user_id: body.user_id,
          user_md: [
            {
              id: 1,
              title: body.title,
              label: body.label,
              content: body.content,
              createTime: body.createTime,
              read: 0,
              recommend: 0,
              good: 0,
            },
          ],
        }).save((err, suc) => {
          err ? reject(err) : resolve(suc);
        });
      });
    }
  });
}

module.exports = {
  getMd,
};
